package com.hangzhou.welbeing.welbeinginstrument.fragement;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hangzhou.welbeing.welbeinginstrument.R;
import com.hangzhou.welbeing.welbeinginstrument.activity.ReleaseTrueCicleActivity;
import com.hangzhou.welbeing.welbeinginstrument.adapter.LifeAllCircleAdapter;
import com.hangzhou.welbeing.welbeinginstrument.base.MyApplication;
import com.hangzhou.welbeing.welbeinginstrument.bean.AddCircleBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.CityWideAllCircleBean;
import com.hangzhou.welbeing.welbeinginstrument.bean.EventRefreshAttentionCicle;
import com.hangzhou.welbeing.welbeinginstrument.config.RBConstants;
import com.hangzhou.welbeing.welbeinginstrument.inteface.OnRecyclerViewItemClickListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 时间 2017 年 09 月 09.
 * 作者 Administrator  刘传华
 * 公司 杭州惟君医疗科技有限公司
 * 包名 com.hangzhou.welbeing.pregnant.welbeing_pregnant.fragement
 * 工程名 welbeing_pregnant
 */
public class LifeAllCircleFragment extends Fragment {
    private static final String TAG ="LifeAllCircleFragment" ;
    @Bind(R.id.fragment_life_all_circle_recyclerView)
    RecyclerView fragmentLifeAllCircleRecyclerView;
    private LifeAllCircleAdapter lifeAllCircleAdapter;
    private List<CityWideAllCircleBean.DataBean> databean;
    private Context context = MyApplication.getMcontext();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(container.getContext(), R.layout.fragment_life_all_circle, null);
        ButterKnife.bind(this, view);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        fragmentLifeAllCircleRecyclerView.setLayoutManager(layoutManager);



        loadLifeAllCircle(1);

        return view;
    }
    /***
     *
     * @desc 生活
     */
    private void loadLifeAllCircle(int p) {
        SharedPreferences sp = context.getSharedPreferences("second_app_internal_data", 0);
        String  user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.ALL_CIRCLE)
                .addParams("pid", "6")
                .addParams("p", p+"")
                .addParams("cus_id", user_id)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String parseNetworkResponse =response.body().string();
                        Gson gson = new Gson();
                       // Log.e(TAG,"parseNetworkResponse===================>"+parseNetworkResponse);
                        final CityWideAllCircleBean cityWideAllCircleBean = gson.fromJson(parseNetworkResponse,CityWideAllCircleBean.class);
                        if(cityWideAllCircleBean.errorCode == 200){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    databean = cityWideAllCircleBean.data;
                                    if(databean != null){
                                        lifeAllCircleAdapter = new LifeAllCircleAdapter(databean,context);
                                        fragmentLifeAllCircleRecyclerView.setAdapter(lifeAllCircleAdapter);

                                        lifeAllCircleAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
                                            @Override
                                            public void onItemClick(View view) {
                                                int position = fragmentLifeAllCircleRecyclerView.getChildAdapterPosition(view);
                                                Intent intent = new Intent(getContext(),ReleaseTrueCicleActivity.class);
                                                intent.putExtra("circle_id",databean.get(position).id);
                                                intent.putExtra("circle_num",databean.get(position).num);
                                                intent.putExtra("circle_name",databean.get(position).cat_name);
                                                intent.putExtra("circle_state",databean.get(position).state+"");
                                                intent.putExtra("circle_url",databean.get(position).url);
                                                startActivity(intent);

                                                SharedPreferences sp =context.getSharedPreferences("second_app_internal_data", 0);
                                                SharedPreferences.Editor edit = sp.edit();
                                                edit.putString("circle_id",databean.get(position).id);
                                                edit.commit();
                                            }

                                            @Override
                                            public void onItemFirstButtonClick(View v, int position) {
                                                TextView textView= (TextView) v;
                                                int state = databean.get(position).state;
                                                String id = databean.get(position).id;
                                                if(state == 0){
                                                    addCircle(id,textView);
                                                }else if(state == 1){
                                                    cancel(id,textView);
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getContext(),cityWideAllCircleBean.errorMessage,Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });

    }
    private void addCircle(String id, final TextView textView) {
        SharedPreferences sp = MyApplication.getMcontext().getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.ADD_CIRCLE)
                .addParams("cat_id", id)
                .addParams("cus_id", user_id)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String praiseParseNetworkResponse =  response.body().string();
                        Gson gson = new Gson();
                        // Log.e(TAG,"praiseParseNetworkResponse============>"+praiseParseNetworkResponse);
                        final AddCircleBean addCircleBean = gson.fromJson(praiseParseNetworkResponse,AddCircleBean.class);
                        if(addCircleBean.errorCode == 200 ){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                   // textView.setText("已关注");
                                    EventBus.getDefault().post(new EventRefreshAttentionCicle("refrech"));
                                    Toast.makeText(MyApplication.getMcontext(),"添加成功",Toast.LENGTH_SHORT).show();
                                    loadLifeAllCircle(1);
                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MyApplication.getMcontext(),addCircleBean.errorMessage,Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }

    /**
     * @desc 取消
     * @param id
     * @param textView */
    private void cancel(String id, final TextView textView) {
        SharedPreferences sp = MyApplication.getMcontext().getSharedPreferences("second_app_internal_data", 0);
        String user_id = sp.getString("user_id","");
        OkHttpUtils
                .post()
                .url(RBConstants.SERVER_URL+RBConstants.CANCEL_JOIN)
                .addParams("cat_id",id)
                .addParams("cus_id", user_id)
                .build()
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String praiseParseNetworkResponse =  response.body().string();
                        Gson gson = new Gson();
                        //  Log.e(TAG,"praiseParseNetworkResponse============>"+praiseParseNetworkResponse);
                        final AddCircleBean addCircleBean = gson.fromJson(praiseParseNetworkResponse,AddCircleBean.class);
                        if(addCircleBean.errorCode == 200 ){
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    //textView.setText("加入");
                                    EventBus.getDefault().post(new EventRefreshAttentionCicle("refrech"));
                                    Toast.makeText(MyApplication.getMcontext(),"已取消",Toast.LENGTH_SHORT).show();
                                    loadLifeAllCircle(1);
                                }
                            });
                        }else{
                            MyApplication.getmHandler().post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(MyApplication.getMcontext(),addCircleBean.errorMessage,Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(Object response, int id) {

                    }
                });
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
